import { Input, Text, Textarea, View } from "@tarojs/components";
import {
  Dialog,
  Image,
  Button,
  Divider,
  Avatar,
  Backdrop,
  Swiper,
} from "@taroify/core";
import diyiImg from "@/assets/images/word/diyi.png";
import meinvImg from "@/assets/images/word/meinv.png";
import mixinImg from "@/assets/images/word/mixin.png";
import yixueImg from "@/assets/images/word/yixue.png";
import zhengzhiImg from "@/assets/images/word/zhengzhi.png";
import otherImg from "@/assets/images/word/other.png";
import man from "@/assets/images/icon/man.png";
import woman from "@/assets/images/icon/woman.png";
import unknown from "@/assets/images/icon/unknown.png";
import { delWordApi, editWordApi, saveOrDeleteMemeApi } from "@/api";
import Taro from "@tarojs/taro";
import { useState } from "react";
import { InfoProps, WordProps } from "@/types/props";
import MyInput from "@/components/common/MyInput";
import { Fire } from "@taroify/icons";
import { imgAddPrefix, saveImageToAlbum, strToArray } from ".";
import { getUser } from "./auth";

export function WordType({
  type,
  size = 70,
  select,
  onChange,
  className,
}: WordProps) {
  let img: string;
  let text: string;

  switch (type) {
    case "diyi":
      text = "极限用语";
      img = diyiImg;
      break;
    case "meinv":
      text = "色情相关";
      img = meinvImg;
      break;
    case "mixin":
      text = "封建迷信";
      img = mixinImg;
      break;
    case "yixue":
      text = "医疗用语";
      img = yixueImg;
      break;
    case "zhengzhi":
      text = "政策相关";
      img = zhengzhiImg;
      break;
    default:
      text = "其他";
      img = otherImg;
      break;
  }
  return (
    <View
      onClick={() => onChange && onChange(type)}
      style={{ backgroundColor: select ? "#EFEBFE" : "transparent" }}
      className={`${className} "flex p-2 rounded-2xl justify-center items-center flex-col text-xs "`}
    >
      <Image width={size} height={size} src={img} />
      <View>{text}</View>
    </View>
  );
}

export const RenderWordsType = ({
  type,
  item,
  reload,
  size = 50,
}: WordProps) => {
  const [edit, setEdit] = useState(false);
  const [value, setValue] = useState(item?.kword);

  return (
    <View className="flex justify-between items-center  py-1 px-3 bg-white rounded-xl ">
      <View className="flex items-center justify-center">
        <WordType type={type} size={size} className="w-12" />
        {item && <View className="text-xs ml-2">{item.kword}</View>}
      </View>
      {item && (
        <View className="w-14 flex justify-between text-xs">
          <Text className="text-[#8A87DA]" onClick={() => setEdit(true)}>
            编辑
          </Text>
          <Text
            className="text-[#A24128]"
            onClick={() =>
              Taro.showModal({
                title: "删除",
                content: "确定删除敏感词吗？！",
                success: function (res) {
                  if (res.confirm)
                    delWordApi(item.kid).then(() => reload && reload());
                },
              })
            }
          >
            删除
          </Text>
        </View>
      )}
      <Dialog open={edit} onClose={setEdit}>
        <Dialog.Header>{item?.type}</Dialog.Header>
        <Dialog.Content>
          <MyInput value={value} change={setValue} />
        </Dialog.Content>
        <Dialog.Actions>
          <Button onClick={() => setEdit(false)}>取消</Button>
          <Button
            onClick={() =>
              editWordApi({
                ...item,
                kword: value ?? "",
                type: item?.type ?? "diyi",
              }).then(() => {
                reload && reload();
                setEdit(false);
              })
            }
          >
            确认
          </Button>
        </Dialog.Actions>
      </Dialog>
    </View>
  );
};

export const RenderMultilineText = (text) => {
  const lines = text.split("\n");
  return lines.map((line, index) => (
    <Text key={index} className="my-1">
      {line}
      {index < lines.length - 1 && <Text>{"\n"}</Text>}{" "}
      {/* 除最后一行外，添加换行 */}
    </Text>
  ));
};

export const RenderInfoBetween = ({
  title,
  right,
  type = "node",
  placeholder = "请输入",
  value,
  change,
  k,
  textDirection = "right",
  message,
  onSubmit,
}: InfoProps) => {
  const [a, setA] = useState(value);
  function onChange(e) {
    setA(e.target.value);
    change && change(k ?? "", e.target.value);
  }
  return (
    <View>
      <View className="flex justify-between gap-1  text-xs">
        <View className=" flex-shrink-0">
          {title} <Text className="text-red-600">*</Text>{" "}
        </View>
        <View className="">
          {type === "input" ? (
            <Input
              className={`text-${textDirection} text-[#B0B0B0]`}
              placeholder={placeholder}
              value={a}
              onInput={onChange}
            />
          ) : type === "textarea" ? (
            <Textarea
              maxlength={800}
              className="text-[#B0B0B0] "
              placeholder={placeholder}
              value={a}
              onInput={onChange}
              autoHeight // 自动调整高度以适应内容
            />
          ) : (
            <View className="text-[22px] text-gray-400">{right}</View>
          )}
        </View>
      </View>
      <Divider />
    </View>
  );
};

export const RenderManOrWoman = (type = 0) => {
  switch (type) {
    case 0:
      return <Image className="w-4 h-4 rounded-full" src={man} />;
    case 1:
      return <Image className="w-4 h-4 rounded-full" src={woman} />;
    default:
      return <Image className="w-4 h-4 rounded-full" src={unknown} />;
  }
};

export const RenderFireIcon = (str: string) => {
  const containsD = /\d+人/.test(str);
  return (
    <View className="flex items-center  text-[#305888] bg-[#1F2C55] p-1 rounded">
      <View>{containsD ? <Fire /> : null}</View>
      <View className="max-w-20 truncate">{str}</View>
    </View>
  );
};

interface tagItem {
  id: string | number;
  label: string;
  iamge?: string;
}

export const RenderTagList = ({
  tags,
  onClick,
  show = false,
}: {
  tags: Array<tagItem>;
  onClick?: (id: string | number, tag?: tagItem) => void;
  show?: boolean;
}) => {
  const [check, setCheck] = useState<string | number>("");
  return (
    <View
      style={{ maxHeight: show ? "auto" : "4rem" }}
      className="flex gap-2 flex-wrap  overflow-hidden my-2"
    >
      {tags.map((tag) => (
        <View
          key={tag.id}
          className={` ${
            check == tag.id
              ? "bg-[#EAF0FE] text-[#7C94DD]"
              : "text-[#303030] bg-[#F7F7F7]"
          } text-xs max-w-32 flex gap-1 items-center truncate  py-1 px-2  rounded-xl`}
          onClick={() => {
            setCheck(tag.id);
            onClick && onClick(tag.id);
          }}
        >
          <Avatar
            src={imgAddPrefix(tag.iamge ?? "")}
            size="mini"
            shape="rounded"
          />
          <View>{tag.label}</View>
        </View>
      ))}
    </View>
  );
};

export const RenderMultilineImage = ({
  images,
  width = 200,
  height = 200,
}: {
  images: string;
  width?: number;
  height?: number;
}) => {
  const imgs = strToArray(images);
  const [open, setOpen] = useState(false);
  const [current, setCurrent] = useState(0);
  return (
    <View onClick={(e) => e.stopPropagation()} className="flex gap-1 flex-wrap">
      {imgs.map((img, i) => (
        <Image
          key={i}
          mode="aspectFill"
          className=" rounded"
          width={width}
          height={height}
          src={img}
          onClick={(e) => {
            setOpen(true);
            setCurrent(i);
            Taro.hideTabBar();
          }}
        />
      ))}
      <Backdrop
        open={open}
        closeable
        onClose={(e) => {
          setOpen(e);
          Taro.showTabBar();
        }}
      >
        <View className="flex items-center justify-center h-full ">
          <Swiper
            lazyRender
            loop={false}
            className="w-screen"
            onChange={setCurrent}
            value={current}
          >
            {imgs.map((item, i) => (
              <Swiper.Item key={i}>
                <Image
                  className="rounded h-full w-screen"
                  mode="widthFix"
                  src={item}
                />
              </Swiper.Item>
            ))}
          </Swiper>
        </View>
        <View className="absolute bottom-3 flex justify-between inset-x-0 mx-4 text-white">
          <View>
            {current + 1}/{imgs?.length}
          </View>
          <View className="flex gap-3" onClick={(e) => e.stopPropagation()}>
            <View
              onClick={() => {
                saveOrDeleteMemeApi({
                  userId: getUser().kid,
                  memeUrl: imgs[current],
                });
              }}
            >
              保存到表情
            </View>
            <View onClick={() => saveImageToAlbum(imgs[current] ?? "")}>
              保存
            </View>
          </View>
        </View>
      </Backdrop>
    </View>
  );
};

export const RenderTitle = ({
  handle,
  menus = ["文章", "帖子", "求助"],
}: {
  menus?: string[];
  handle: (i: number) => void;
}) => {
  const [select, setSelect] = useState(0);
  return (
    <View className="flex gap-3 w-full justify-center items-center">
      {menus.map((menu, i) => (
        <View
          onClick={() => {
            setSelect(i);
            handle(i);
          }}
          key={i}
          className={`w-10 flex justify-center items-center flex-col ${
            select == i ? "font-bold text-black " : ""
          }`}
        >
          {menu}
          <View
            className={`"w-5 h-1 rounded-full mt-1 ${
              select == i ? "bg-blue-400" : "transparent"
            }"`}
          ></View>
        </View>
      ))}
    </View>
  );
};
